package com.md.album.ui;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.md.album.R;
import com.md.album.adapter.AlbumListAdapter;
import com.md.album.db.SelfAlbumManager;
import com.md.album.utils.AlbumUtil;
import com.md.basedpc.base.BaseActivity;
import com.md.basedpc.routerservice.NotifyService;
import com.md.livingwidget.dialog.PHDialogBackLinstenerImpl;
import com.md.livingwidget.dialog.PHDialogUtils;
import com.md.livingwidget.navigation.PHNavigationBar;
import com.md.livingwidget.toast.PHToast;
import com.md.network.api.Album;
import com.md.network.api.Audio;

import java.util.ArrayList;
import java.util.List;

import static com.md.basedpc.constant.BaseConstant.SELF_CREATE_ALBUM;

/**
 * @author liyue
 * des: 专辑列表页，供选中的音频添加；
 */
@Route(path = "/album/albumlist")
public class AlbumListActivity extends BaseActivity implements AlbumListAdapter.OnItemClickListener{
    public static final String SELECTED_AUDIOS="SELECTED_AUDIOS";
    private PHNavigationBar navigationBar;
    private RecyclerView recAlbums;
    private AlbumListAdapter adapter;
    private ArrayList<Audio> selectedAudios = new ArrayList<>();
    private ArrayList<Album> albums = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_album_list);
        ARouter.getInstance().inject(this);
        initData();
        initNav();
        initView();
    }

    private void initView() {
        recAlbums = findViewById(R.id.recAlbums);
        adapter = new AlbumListAdapter(this,this,albums);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recAlbums.setLayoutManager(layoutManager);
        recAlbums.setAdapter(adapter);
    }

    private void initData(){
        Intent intent = getIntent();
        if (intent.hasExtra(SELECTED_AUDIOS)){
            ArrayList<Audio> audios = intent.getParcelableArrayListExtra(SELECTED_AUDIOS);
            selectedAudios.addAll(audios);
        }
        Album createAlbum = new Album(new ArrayList<Audio>(),"UNKNOWN",getLocalPicPath(this,R.drawable.album_create_new_album),getString(R.string.album_create_self_album),"-1",0,getString(R.string.album_create_self_album),null);
       List<Album> allSelfAlbums =  SelfAlbumManager.getIns().getAllSelfAlbum();
       if (allSelfAlbums !=null){
           albums.add(createAlbum);
           albums.addAll(allSelfAlbums);
       }
    }

    private void initNav(){
        navigationBar = findViewById(R.id.navBar);
        String title = String.format(getResources().getString(R.string.album_add_audios),String.valueOf(selectedAudios.size()));
        navigationBar.getCenterTvTitle().setText(title);
        navigationBar.getRight2Tv().setText(getString(R.string.album_close));
        navigationBar.getRight2Tv().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlbumListActivity.this.finish();
            }
        });
    }

    private String getLocalPicPath(Context context, int id){
        return getUriFromDrawableRes(context,id).toString();
    }

    public Uri getUriFromDrawableRes(Context context, int id) {
        Resources resources = context.getResources();
        String path = ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + resources.getResourcePackageName(id) + "/"
                + resources.getResourceTypeName(id) + "/"
                + resources.getResourceEntryName(id);
        return Uri.parse(path);
    }

    @Override
    public void onItemClick(Album curAlbum, int curPos) {
        if (curPos == 0){
            showDialog();
        }else {
            addAudiosToAlbum(curAlbum);
            finish();
        }
    }

    private void addAudiosToAlbum(Album curAlbum){
        int count=0;
        for (Audio audio:selectedAudios){
            boolean isSuc = addAudioToAlbum(curAlbum,audio);
            if (isSuc) {
                count++;
            }
        }
        ARouter.getInstance().navigation(NotifyService.class).selfAlbumUpdateSuc(SELF_CREATE_ALBUM);
        PHToast.shotBigToast(this,String.format(getString(R.string.album_add_audios_suc),String.valueOf(count),curAlbum.getName()));
    }

    private boolean addAudioToAlbum(Album curAlbum, Audio audio){
        boolean isSuc = SelfAlbumManager.getIns().saveAudioToAlbum(String.valueOf(curAlbum.getId()),audio);
        return isSuc;
    }

    private void showDialog() {
        PHDialogUtils.showEdit(this, null, "新建专辑", new PHDialogBackLinstenerImpl() {
                    @Override
                    public void rightBtn(String res) {
                        super.rightBtn(res);
                    }

                    @Override
                    public void leftBtn(String res) {
                        super.leftBtn(res);
                        createAlbumAndaddAudios(res);
                    }
                }
                , 100, true, "");
    }

    private void createAlbumAndaddAudios(String title) {
        if (TextUtils.isEmpty(title)) {
            Toast.makeText(this, getString(R.string.album_notempty_title), Toast.LENGTH_SHORT).show();
            return;
        }
        int albumId = AlbumUtil.INSTANCE.getAlbumId();
        Album album = new Album(new ArrayList<Audio>(), "", "", "", String.valueOf(albumId), 0, title,null);
        boolean isSuc = SelfAlbumManager.getIns().saveAlbum(album);
        if (isSuc){
            addAudiosToAlbum(album);
            finish();
        }
    }
}
